package com.example.administrator.fastdream.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.example.administrator.fastdream.R;
import com.example.administrator.fastdream.date.bean.BaseBean;
import com.example.administrator.fastdream.date.bean.CitySelectBean;
import com.example.administrator.fastdream.date.bean.PersonalInfoBean;
import com.example.administrator.fastdream.date.bean.UploadPhotoBean;
import com.example.administrator.fastdream.date.presenter.PersonalInfoPresenter;
import com.example.administrator.fastdream.date.utils.DimenUtil;
import com.example.administrator.fastdream.date.utils.MyUtils;
import com.example.administrator.fastdream.date.utils.PhotoHelper;
import com.example.administrator.fastdream.view.base.BaseActivity;
import com.example.administrator.fastdream.view.base.BaseDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MineActivity extends BaseActivity implements PersonalInfoPresenter.PersonCallBack {

    @BindView(R.id.iv_mine)
    ImageView ivMine;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.iv_photo)
    ImageView iv_photo;
    @BindView(R.id.fl_head)
    FrameLayout flHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    private BaseDialog mDialog;
    private BaseDialog.Builder mBuilder;
    private List<CitySelectBean> options1Items = new ArrayList<>();
    private List<ArrayList<String>> options2Items = new ArrayList<>();
    private List<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private PersonalInfoPresenter presenter;
    private boolean isChangeHead;
    private PersonalInfoBean.DataEntity.UserInfoEntity user_info;
    private String filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        ButterKnife.bind(this);
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setText("我的");
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        presenter = new PersonalInfoPresenter(this, this);
        presenter.getPersonalInfo();
    }

    private void showModifyInfoDialog(final TextView tvmodel, String title, String content) {
        mBuilder = new BaseDialog.Builder(this);
        int dialog_width = MyUtils.getScreenWidth(this) - DimenUtil.dp2px(this, 40);
        int dialog_height = (int) (dialog_width / 2f);
        mDialog = mBuilder.setViewId(R.layout.dialog_modify_info)
                //设置dialogpadding
                .setPaddingdp(20, 0, 20, 0)
                //设置显示位置
                .setGravity(Gravity.CENTER)
                //设置动画
                .setAnimation(R.style.Alpah_aniamtion)
                //设置dialog的宽高
                .setWidthHeightpx(LinearLayout.LayoutParams.MATCH_PARENT, dialog_height)
                //设置触摸dialog外围是否关闭
                .isOnTouchCanceled(true)
                //设置监听事件
                .builder();
        mDialog.show();
        TextView tv_title = mDialog.getView(R.id.tv_title);
        tv_title.setText(title);
        final EditText et_content = mDialog.getView(R.id.et_content);
        et_content.setText(content.equals("请填写") ? "" : content);
        mDialog.getView(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.getView(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvmodel.setText(et_content.getText().toString());
                mDialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // sample1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    filePath = selectList.get(0).getCompressPath();
                    Glide.with(mContext).load(filePath).into(ivHead);
                    iv_photo.setVisibility(View.GONE);
                    isChangeHead = true;
                    break;
            }
        }
        //提现之后刷新金额
        if (resultCode==MyWalletActivity.RESULTCODE){
            presenter.getPersonalInfo();
        }
    }

    @OnClick({R.id.iv_back, R.id.fl_head, R.id.tv_name, R.id.tv_city, R.id.tv_address, R.id.tv_money, R.id.tv_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                doSaveInfo();
                finish();
                break;
            case R.id.fl_head:
                PhotoHelper.choosePhoto(this, 1,
                        DimenUtil.dp2px(this, 102), DimenUtil.dp2px(this, 102));
                break;
            case R.id.tv_name:
                showModifyInfoDialog(tvName, "修改昵称", tvName.getText().toString());
                break;
            case R.id.tv_city:
                if (isLoaded) {
                    chooseCity();
                }
                break;
            case R.id.tv_address:
                showModifyInfoDialog(tvAddress, "修改地址", tvAddress.getText().toString());
                break;
            case R.id.tv_money:
                Intent intent = new Intent(mContext, MyWalletActivity.class);
                startActivityForResult(intent,0);
                break;
            case R.id.tv_record:
                startActivity(new Intent(mContext, MyRecordActivity.class));
                break;
        }
    }

    @Override
    public void onBackPressed() {
        doSaveInfo();
        super.onBackPressed();
    }

    private void doSaveInfo() {
        if (isChangeHead) {
            presenter.uploadPhotos(new File(filePath));
        } else {
            String name = TextUtils.equals(tvName.getText().toString(), user_info.getUsername()) ? "" : tvName.getText().toString();
            String city = TextUtils.equals(tvCity.getText().toString(), user_info.getCity_name()) ? "" : tvCity.getText().toString();
            String address = TextUtils.equals(tvAddress.getText().toString(), user_info.getAddress()) ? "" : tvAddress.getText().toString();
            if (name.equals("") && city.equals("") && address.equals("")) {
                //不做改动
            } else {
                presenter.savePersonalInfo("", name, city, address);
            }
        }
    }

    private void chooseCity() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (TextUtils.equals(options1Items.get(options1).getPickerViewText(), options2Items.get(options1).get(options2))) {
                    tvCity.setText(options1Items.get(options1).getPickerViewText());
                } else {
                    String tx = options1Items.get(options1).getPickerViewText()
                            + options2Items.get(options1).get(options2)
                            /* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/;
                    tvCity.setText(tx);
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器*/
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<CitySelectBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<CitySelectBean> parseData(String result) {//Gson 解析
        ArrayList<CitySelectBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                CitySelectBean entity = gson.fromJson(data.optJSONObject(i).toString(), CitySelectBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void getPersonalInfo(PersonalInfoBean personalInfoBean) {
        user_info = personalInfoBean.getData().getUser_info();
        String avatar = user_info.getAvatar();
        if (!TextUtils.isEmpty(avatar)) {
            Glide.with(mContext).load(avatar).into(ivHead);
            iv_photo.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(user_info.getUsername())) {
            tvName.setText(user_info.getUsername());
        }
        if (!TextUtils.isEmpty(user_info.getCity_name())) {
            tvCity.setText(user_info.getCity_name());
        }
        if (!TextUtils.isEmpty(user_info.getAddress())) {
            tvAddress.setText(user_info.getAddress());
        }
        tvMoney.setText(user_info.getBalance());
    }

    @Override
    public void savePersonalInfo(BaseBean baseBean) {

    }

    @Override
    public void uploadPhotos(UploadPhotoBean uploadPhotoBean) {
        String name = TextUtils.equals(tvName.getText().toString(), user_info.getUsername()) ? "" : tvName.getText().toString();
        String city = TextUtils.equals(tvCity.getText().toString(), user_info.getCity_name()) ? "" : tvCity.getText().toString();
        String address = TextUtils.equals(tvAddress.getText().toString(), user_info.getAddress()) ? "" : tvAddress.getText().toString();
        presenter.savePersonalInfo(uploadPhotoBean.getData().getImg(), name, city, address);
    }

}
